package Staff

import (
	"ali-hr/Database"
	"ali-hr/Models"
	"bytes"
	"fmt"
	"github.com/gookit/goutil/dump"
)

/**
 * Created by Goland
 * User: wkk alisleepy@hotmail.com
 * Time: 2021/12/17 - 02:08
 * Desc: <Staff模块业务逻辑处理>
 */

// UserList 员工列表信息
func UserList(pageIndex, pageSize int, filters map[string]interface{}, all bool) ([]Models.Staff, int, error) {
	var staffs []Models.Staff
	var total int
	var Db = Database.SqlDB

	// 搜索条件
	for key, val := range filters {
		if val == 0 || val == "" || val == nil {
			continue
		}
		// 雇佣状态
		if key == "status" {
			Db = Db.Where("status = ?", val)
		}
		if key == "name" {
			Db = Db.Where("name like ?", "%"+val.(string)+"%")
		}
		if key == "job_no" {
			var bt bytes.Buffer
			bt.WriteString("%")
			bt.WriteString(fmt.Sprintf("%v", val))
			bt.WriteString("%")
			Db = Db.Where("job_no like ?", bt.String())
		}
		if key == "department_id" {
			Db = Db.Where("department_id = ?", val)
		}
		if key == "leader_id" {
			Db = Db.Where("leader_id = ?", val)
		}
	}

	// 是否获取所有
	if all == true {
		// 关联：leader表、department表
		err := Db.Preload("Leader").
			Preload("Department").
			Find(&staffs).Error
		if err != nil {
			return nil, 0, err
		}
	} else {
		// 分页操作，offset 和 limit
		err := Db.Preload("Leader").
			Preload("Department").
			Offset((pageIndex - 1) * pageSize).
			Limit(pageSize).
			Find(&staffs).Error
		if err != nil {
			return nil, 0, err
		}
	}
	return staffs, total, nil
}

// GetUserInfo 查看单个员工信息
func GetUserInfo() {

}

// UpdateUser 更新员工信息
func UpdateUser() {

}

// Resign StaffResign 员工离职操作，修改雇佣状态信息
func Resign() {

}

// ExportExcel 导出员工信息到excel
func ExportExcel() {

}

// AllStaffs 所有员工信息
func AllStaffs() []Models.Staff {
	var staffs []Models.Staff
	err := Database.SqlDB.Select([]string{"id", "name", "department_id", "department_name"}).
		Where("status = ?", Models.INCUMBENT).
		Find(&staffs).Error
	if err != nil {
		dump.P("获取所有员工失败，err:", err)
		return nil
	}
	return staffs
}
